<?php 
//get all the bookmarks
include("./class.iniparser.php");
$cfg = new iniParser("../../configuration/config.ini");
//include the postrequest code for calling the remote APIs
include("./postrequest.php");
//include("chunkeddecoder.php");
//require_once("transfer_encoding_chunked_decode.lib.php");
$bookmarklogs = "../../logs/bookmarks.log";

//get the saved variables
$config_newzuname = $cfg->get("Newzbin","username"); 
$config_newzpw = $cfg->get("Newzbin","password");
$config_NZBDropPath = $cfg->get("Newzbin","NZBDropPath");
$config_deleteupondl = $cfg->get("Newzbin","deleteupondl");
$config_memory_limit = $cfg->get("System","memory_limit");

$currdt = date("Y-m-d");
$currtime = date("g:i a");
if($config_newzuname == "" || $config_newzpw == ""){ die("[WARNING] ($currdt) (". date("g:i a") .") Username and/or password are not set.\n"); }
//echo "[INFO] ($currdt) (". date("g:i a") .") The following bookmarks have been downloaded to the $config_NZBDropPath directory.\n\n";
//use the new post-request code to pull back the reports
// submit these variables to the server:
$data = array(
    'username' => $config_newzuname,
    'password' => $config_newzpw,
    'action' => 'fetch'
);
// send a request
list($header, $content) = PostRequest(
    "http://www.newzbin.com/api/bookmarks/",
    "http://popcornhour/NewzBook_web/index.php?action=testbookmarkdownload",
    $data
);
// parse out the header and get each line
$HeaderLines = explode("\n", $header);
$httpstatus = explode(" ", $HeaderLines[0]);
if($httpstatus[1] != 200 && $httpstatus[1] != 204) { 
    switch ($httpstatus[1]) {
        case 400: 
            echo "[ERROR] ($currdt) (". date("g:i a") .") Bad Request. Newzbin didn't understand your request. Check the parameters.\n";
            break;
        case 401:
            echo "[ERROR] ($currdt) (". date("g:i a") .") Unauthorized. Check your username and password.\n";
            break;
        case 402: 
            echo "[ERROR] ($currdt) (". date("g:i a") .") Payment Required (the account is not a premium account)\n";
            break;
        case 403:
            echo "[ERROR] ($currdt) (". date("g:i a") .") Forbidden. Check your username and password.\n";
            break;
        case 500: 
            echo "[ERROR] ($currdt) (". date("g:i a") .") Internal Server Error (Newzbin broke)\n";
            break;
        case 503: 
            echo "[ERROR] ($currdt) (". date("g:i a") .") Service Unavailable, site is currently down\n";
            break;
        default:
            if($httpstatus[1] != 200) { echo "Unknown error with HTTP response code $httpstatus[1]\n"; };
    } 
} elseif($httpstatus[1] == 204){ echo "[INFO] ($currdt) (". date("g:i a") .") There are no bookmarks in your account.\n"; }
elseif($httpstatus[1] == 200){echo "[INFO] ($currdt) (". date("g:i a") .") The following bookmarks have been downloaded to the $config_NZBDropPath directory.\n";}

//loop through the array of bookmarks associating each bookmark to a variable
// split the content into each line
$ContentLines = explode("\n", $content);
// for each line, lets format the data we get from Newzbin
foreach($ContentLines as $CurrLine) {
    //echo $CurrLine;
    if(preg_match('/[0-9]+\t[0-9]+\t.+/', $CurrLine)) {
        // split each line into the different variables
        $SplitContent = explode("\t", $CurrLine);
        //tell the user what file we are downloading
        echo "[INFO] (". date("g:i a") .")Attempting to download $SplitContent[2] via newzbin report $SplitContent[0] \n";
        //download the NZB
        //use the new post-request code to pull back the reports
        // submit these variables to the server:
        $data = array(
            'username' => $config_newzuname,
            'password' => $config_newzpw,
            'reportid' => $SplitContent[0]
        );
         
        // send a request
        list($header, $content) = PostRequest(
            "http://www.newzbin.com/api/dnzb/",
            "http://popcornhour/NewzBook_web/index.php",
            $data
        );
        
        // parse out the header and get each line
        $HeaderLines = explode("\n", $header);
        // for each line, lets format the data we get from Newzbin
        foreach($HeaderLines as $CurrLine) {
            //make sure it's a line with a variable
            preg_match('/([^:]+): (.+)/',$CurrLine,$HdrLineContent);         
            //if the variables are set clean and assign them
            if(isset($HdrLineContent[1]) && isset($HdrLineContent[2])) {
                //remove dash from header
                $HdrLineContent[1] = str_replace("-","_",$HdrLineContent[1]);
                //assign content to variable name
                ${$HdrLineContent[1]} = $HdrLineContent[2];
            }
        }

        if($X_DNZB_RCode == 200) {
            //create string replacement arrays, then clean up the filename using those
            $dirty2dash = array("/");
            $nzbfilename = str_replace($dirty2dash,"-",trim($X_DNZB_Name));
            $dirty2remove = array(":");
            $nzbfilename = str_replace($dirty2remove,"",$nzbfilename);
            //create the NZB in the NZB library
            $nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb";
            //echo "I'm going to write to the file: $nzbfilename <br/>";
            $fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br/>");
            if($fh != FALSE) {
                echo "[INFO] (". date("g:i a") .")Writing to file $nzbfilename \n";
                if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br/>");
                    //We successfully wrote the NZB, lets remove it from the bookmarks if the user wants
                    if($config_deleteupondl == "delon"){
                        $data = array(
                            'username' => $config_newzuname,
                            'password' => $config_newzpw,
                            'action' => 'delete',
                            'reportids' => $SplitContent[0]
                        );
                         
                        // send a request
                        list($deleteheader, $deletecontent) = PostRequest(
                            "http://www.newzbin.com/api/bookmarks/",
                            "http://popcornhour/NewzBook_web/index.php",
                            $data
                        );
                        echo "[INFO] (". date("g:i a") .")Removing reportID $SplitContent[0] from newzbin bookmarks \n";
                    } else { echo "[INFO] (". date("g:i a") .")Delete option is turned off. Report $SplitContent[0] will stay in your bookmarks \n"; }
                } else { echo "[WARNING] (". date("g:i a") .")Can't write to file $nzbfilename \n"; }
                fclose($fh);
            } else { echo "[WARNING] (". date("g:i a") .")Couldn't open file $nzbfilename \n"; }
            echo "Current Memory: ".memory_get_usage()." | Peak Memory: ".memory_get_peak_usage()."\n";
            echo "\n";
            //exit;
        } 
        else { 
            echo "[WARNING] (". date("g:i a") .")Error with response code: $X_DNZB_RCode"; 
            echo "[WARNING] (". date("g:i a") .")Error Message: $X_DNZB_RText \n";
        }
    }
}
//echo "\n";